package cycling.taxi.com.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cycling.taxi.com.R;
import cycling.taxi.com.entity.Tips;
import cycling.taxi.com.ui.activity.WebsiteMapAty;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.ToastUtil;
import cycling.taxi.com.utils.Urls;

/**
 * Created by Administrator on 2017/5/4.
 */
public class WebsiteFrgt extends Fragment implements AbsListView.OnScrollListener {
  /*  @InjectView(R.id.website_view_btmap)
    LinearLayout mWebsiteViewBtmap;
    @InjectView(R.id.website_view_imagmap)
    ImageView mWebsiteViewImagmap;*/
    @InjectView(R.id.listView)
    ListView mlistView;
    private RequestQueue queue;
    private ListViewAdapter adapter;
    private ArrayList<Tips>data;
    private ArrayList<Tips>datas;
    private View view_more;
    private ProgressBar pb;
    private TextView tvLoad;
    private int lastVisibleIndex;
    private int start, end;
    private int totalCount = 100;
    private int pageCount=1;
    private int pageNo=1;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.frgt_website_view, null);
       // View view = LayoutInflater.from(this.getContext()).inflate(R.layout.frgt_tips_lv, null);
        queue= Volley.newRequestQueue(this.getContext());
        initUI(view);
        initData();
        ButterKnife.inject(this,view);
        return view;
    }
    public void volleyGet(){
        String path= Urls.getTips();
        StringRequest request = new StringRequest(path, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                String [] split;
                LogUtil.e("贴士"+s);
                split=s.split("=");
                pageCount=Integer.parseInt(split[0]);
                data = new Gson().fromJson(split[1],new TypeToken<List<Tips>>(){}.getType());
                adapter = new ListViewAdapter();
                mlistView.setAdapter(adapter);
                mlistView.addFooterView(view_more);
                setListeners();
            }
        },null);
        queue.add(request);
    }
    private void initUI(View view) {
       // mlistView = (ListView) view.findViewById(R.id.);
        view_more =LayoutInflater.from(getActivity()).inflate(R.layout.view_more, null);
        //view_more = (View) getLayoutInflater().inflate(R.layout.view_more, null);
        // 进度条
        pb = (ProgressBar) view_more.findViewById(R.id.progressBar);
        // “正在加载...”文本控件
        tvLoad = (TextView) view_more.findViewById(R.id.tv_Load);
    }
    private void initData() {
        volleyGet();
        //   mTipsLv.setAdapter(new ListViewAdapter());
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        Log.e("TAG", "lastVisibleIndex = " + lastVisibleIndex);
        Log.e("TAG", "adapter.getCount() = " + adapter.getCount());
        // 滑到底部后自动加载，判断listView已经停止滚动并且最后可视的条目等于adapter的条目
        // 注意这里在listView设置好adpter后，加了一个底部加载布局。
        // 所以判断条件为：lastVisibleIndex == adapter.getCount()
        if (scrollState == SCROLL_STATE_IDLE
                && lastVisibleIndex == adapter.getCount()) {
            /**
             * 这里也要设置为可见，是因为当你真正从网络获取数据且获取失败的时候。
             * 我在失败的方法里面，隐藏了底部的加载布局并提示用户加载失败。所以再次监听的时候需要
             * 继续显示隐藏的控件。因为我模拟的获取数据，失败的情况这里不给出。实际中简单的加上几句代码就行了。
             */
            pb.setVisibility(View.VISIBLE);
            tvLoad.setVisibility(View.VISIBLE);
            loadMoreData();// 加载更多数据
        }
    }
    private void loadMoreData() {
        // 获取此时adapter中的总条目数
        int count = adapter.getCount();
        // 一次加载15条数据，即下拉加载的执行
        if (pageNo<pageCount) {

            volleyGet2();
            // initData(start, end);// 模拟网络获取数据操作
        }

    }
    public void volleyGet2(){
        String path= Urls.getTips();
        StringRequest request = new StringRequest(path, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                String [] split;
                LogUtil.e("贴士"+s);
                split=s.split("=");
                datas = new Gson().fromJson(split[1],new TypeToken<List<Tips>>(){}.getType());
                for(int i=0;i<datas.size();i++){
                    data.add(datas.get(i));

                }
                adapter.notifyDataSetChanged();
            }
        },null);
        queue.add(request);
    }
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
        // 当adapter中的所有条目数已经和要加载的数据总条数相等时，则移除底部的View
        if (totalItemCount == pageCount*4 + 1) {
            // 移除底部的加载布局
            Toast.makeText(getActivity(), "数据已经全部加载", Toast.LENGTH_LONG).show();
            mlistView.removeFooterView(view_more);
        }
    }
    private void setListeners() {
        if (totalCount > 15) {
            // listView设置滑动简监听
            mlistView.setOnScrollListener(this);
        } else {
            // 假如数据总数少于等于15条，直接移除底部的加载布局，不需要再加载更多的数据
            mlistView.removeFooterView(view_more);
        }
    }
    /*
        @OnClick({R.id.website_view_btmap, R.id.website_view_imagmap})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.website_view_btmap:
                    startToWebsiteMapAty();
                    break;
                case R.id.website_view_imagmap:
                    startToWebsiteMapAty();
                    break;
            }
        }

        private void startToWebsiteMapAty() {
            Intent intent = new Intent(this.getActivity(), WebsiteMapAty.class);
            startActivity(intent);
        }
    */
public class ListViewAdapter extends BaseAdapter {

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TipsFrgt.ViewHolder holder=null;
        if (convertView==null) {
            convertView = LayoutInflater.from(getActivity()).inflate(R.layout.lv_web_item, null);
        }
        Tips tips = data.get(position);
        Log.e("tag",tips.getContent());
        holder = new TipsFrgt.ViewHolder();
        holder.tv = (TextView) convertView.findViewById(R.id.website_tv);
        holder.tv.setText(tips.getContent());

        convertView.setTag(holder);

        return convertView;
    }
}
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
